//产品信息

var Face = require("./Face.js"); //面
var productAttrView = require("./view/productAttrView.js");
var HashMapArray = require("./utils/HashMapArray.js");

function Product(con) {
	this.con = con;
	this.id = ""; //产品id
	this.faces = new HashMapArray(); //产品不同面
	this.colors = []; //颜色
	this.sizes = []; //大小
	this.designType = 0; //设计类型 0:非全衣, 1:全衣
	this.name = "";
	this.currFace = null;
	this.currColor = {};
	this.currSize = {};
}

Product.prototype.setJson = function(data) {
	this.destroy();
	this.id = data.id;
	this.name = data.name;
	this.colors = data.colors;
	this.sizes = data.sizes;
	
	var views = data.faces;
	for (var i = 0; i < views.length; i++) {
		this.addFace(views[i]);
	};
	
	this.currFace = this.faces.getValueAt(0);
	if(data.state){
		var currFaceId = data.state.currFaceId;
		if(currFaceId){
			this.currFace = this.faces.getValue(currFaceId);
		}
		
		this.currColor = data.state.currColor;
		this.currSize = data.state.currSize;
	}
	
	this.activeFace();
	
	productAttrView.bind(this);
}

Product.prototype.addFace = function(data) {
	var face = this.currFace = new Face();
	if (data) {
		face.setJson(data);
	}
	face.faceCon.appendTo(this.con);
	this.faces.push(face.id, face);
	return face;
}

Product.prototype.removeFace = function(id) {
	var face = this.faces.remove(id);
	if (face) {
		face.destroy();
		face = null;
	}
}

Product.prototype.activeFace = function(id){
	var faces = this.faces;
	for (var i = 0; i < faces.length; i++) {
		var face = faces.getValueAt(i);
		face.hide();
	}
	
	if(id){
		this.currFace = faces.getValue(id);
	}
	if(this.currFace){
		this.currFace.show();
	}
	Design.tool.setTarget(null);
	return this.currFace;
}

/* 设置颜色 */
Product.prototype.setColor = function(obj){
	this.currColor = obj;
	for (var i = 0; i < this.faces.length; i++) {
		var face = this.faces.getValueAt(i);
		face.product.setColor(obj);
	}
}

/* 设置大小 */
Product.prototype.setSize = function(obj){
	this.currSize = obj;
}

/*
 * 获取保存的数据
 */
Product.prototype.getSaveData = function() {
	var self = this;
	var json = {
		id: self.id,
		name: self.name,
		colors: self.colors,
		sizes: self.sizes,
		faces: [],
		state: {
			currFaceId: self.currFace.id,
			currColor: self.currColor,
			currSize: self.currSize
		}
	}

	/*
	 * 获取面数据
	 */
	for (var i = 0; i < this.faces.length; i++) {
		var face = this.faces.getValueAt(i);
		var facedata = face.getSaveData();
		json.faces.push(facedata);
	}

	return json;
}

Product.prototype.reset = function(){
	for (var i = 0; i < this.faces.length; i++) {
		var face = this.faces.getValueAt(i);
		face.reset();
	}
}

Product.prototype.destroy = function(){
	var faces = this.faces;
	for (var i = 0; i < faces.length; i++) {
		var face = faces.getValueAt(i);
		this.removeFace(face.id);
	}
	this.faces.clear();
	this.colors = null;
	this.size = null;
}

exports = module.exports = Product;

